package edu.spec.student.controller;

import edu.spec.student.model.event.Event;
import edu.spec.student.service.iface.IEventService;
import edu.spec.basic.model.dto.MvcReturn;
import edu.spec.basic.model.enumeration.Status;
import edu.spec.basic.util.FileTool;
import org.madgecko.basic.model.Pager;
import org.madgecko.basic.util.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * "活动管理"
 */
@Controller
@RequestMapping("/admin/event")
public class EventController {

    @Inject
    private IEventService eventService;

    @ResponseBody
    @RequestMapping("/add")
    public MvcReturn add(Event e){
        e.setCreateDate(new Date());
        eventService.add(e);
        return new MvcReturn(true);
    }

    @RequestMapping("/snapshoot")
    public void uploadSnapshoot(MultipartFile snapshoot, HttpServletRequest req, HttpServletResponse resp){
        try {
            MvcReturn re = null;
            String fullPath = FileTool.saveTempFile(snapshoot, req);
            String[] strs = fullPath.split("\\\\");
            int len = strs.length;
            if(len<=0){
                re = new MvcReturn(false);
            }else{
                String path = strs[len-1];
                re = new MvcReturn(true, path, "操作成功");
            }
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write(JsonUtil.getInstance().obj2json(re));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/delete/{id}")
    public MvcReturn delete(@PathVariable Integer id){
        eventService.delete(id);
        return new MvcReturn(true);
    }

    @ResponseBody
    @RequestMapping("/update")
    public MvcReturn update(Event e){
        eventService.update(e);
        return new MvcReturn(true);
    }

    @ResponseBody
    @RequestMapping("/toggleStatus/{id}")
    public MvcReturn toggleStatus(@PathVariable Integer id){
        eventService.toggleStatus(id);
        return new MvcReturn(true);
    }

    @ResponseBody
    @RequestMapping("/findByCon")
    public MvcReturn findByCon(Status status, String keyword){
        Pager<Event> data = eventService.findByCon(status, keyword);
        return new MvcReturn(true, data.getDatas(), data.getTotal());
    }

}
